# encoding:utf-8
from redis import Redis
import time

ONE_WEEK_IN_SECONDS = 7 * 86400
VOTE_SCORE = 432.0

conn = Redis(host="192.168.35.211", port=6379, db=0)


def article_vote(conn, user, article):
    cutoff = time.time() - ONE_WEEK_IN_SECONDS
    if conn.zscore('time:', article) < cutoff:
        return
    article_id = article.partition(':')[-1]
    if conn.sadd('voted:' + article_id, user):
        conn.zincrby('score:', VOTE_SCORE, article)
        conn.hincrby(article, "votes", 1)


def post_article(conn, user, title):
    article_id = str(conn.incr('article:'))
    add_remove_groups(conn, article_id, ['program'])
    voted = 'voted:' + article_id
    # 存储已经投票的人
    conn.sadd(voted, user)
    # 设置过期时间，一周之内不能再投票
    conn.expire(voted, ONE_WEEK_IN_SECONDS)
    now = time.time()
    article = 'article:' + article_id
    # 存储文章信息
    conn.hmset(article, {
        'title': title,
        'poster': user,
        'time': now,
        'votes': 1
    })
    # 存储初始分数
    conn.zadd('score:', {article: now + VOTE_SCORE})
    # 存储发布时间
    conn.zadd('time:', {article: now})


ARTICLE_PRE_PAGE = 25


def get_articles(conn, page, order="score:"):
    start = (page - 1) * ARTICLE_PRE_PAGE
    end = start + ARTICLE_PRE_PAGE

    ids = conn.zrevrange(order, start, end)
    artcles = []
    for id in ids:
        article_data = conn.hgetall(id)
        article_data['id'] = id
        artcles.append(article_data)


def add_remove_groups(conn, article_id, to_add=[], to_remove=[]):
    article = 'article:' + article_id
    for group in to_add:
        conn.sadd('group:' + group, article)
    for group in to_remove:
        conn.srem('group:' + group, article)


def get_group_articles(conn, group, page, order='score:'):
    key = order + group
    if not conn.exists(key):
        conn.zinterstore(key, ['group:' + group, order], aggregate='max')
        conn.expire(key, 60)
    return get_articles(conn, page, key)


def print_hi(name):
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    #post_article(conn, "hyman:1", "my post1")
    # article_vote(conn, 'tom:2', 'article:1')
    get_articles(conn, 1)
    get_group_articles(conn,'program',1)
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
